# coding:utf-8
import tkinter as tk
import tempfile
import ttkbootstrap as tkBoot

from PIL import ImageTk, Image

tabDict = {}


def inTabs(title) -> bool:
    global tabDict
    return title in tabDict.keys()


def addToTabs(title, tab):
    global tabDict
    tabDict[title] = tab


def removeFromTabs(title):
    global tabDict
    tabDict.pop(title, "不存在" + title)


def get_temp_file():
    return tempfile.gettempdir()


def get_middle_point(window, width, height):
    return int((window.winfo_screenwidth() - width) / 2), int((window.winfo_screenheight() - height) / 2)


def get_image(path, size):
    image = Image.open(path)
    if size is not None:
        image = image.resize(size)
    return ImageTk.PhotoImage(image)


def show_center(element, width, height):
    element.geometry("{}x{}+{}+{}".format(width, height, *get_middle_point(element, width, height)))


def set_bg(imgPath, parent, width, height):
    img = get_image(imgPath, (width, height))
    # 创建标签并添加图像
    bg_label = tkBoot.Label(parent, image=img)
    bg_label.place(x=0, y=0)


def close_tab(notebook, title):
    current_tab = notebook.select()
    if current_tab:
        notebook.forget(current_tab)
        removeFromTabs(title)


def create_close_btn(parent, title):
    close_button = tkBoot.Button(parent, text="X", command=lambda: close_tab(parent.notebook, title),
                                 bootstyle="danger")
    close_button.pack(anchor=tk.NE)
